<?php

class Core_Backend_Component_Website_Controller_Block extends Dcmp_Component_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function indexAction($pageindex = 1, $pagesize = 20, $areaid = 0) {
        $this->getHistory()->record();
        $areas = App::getHelper('global')->getAreas();
        $validator = new Kd_Validation_Validator();
        $validator->setTarget($this->getRequest()->getParameter('filter'));
        if (!$areaid) {
            $areaid = $areas->getFirstItem()->getId();
        }
        $collection = App::getModel('website/collection_block')
                        ->filterByArea($areaid)
                        ->pagination($pageindex, $pagesize);
        if ($validator->isNotEmpty('name')) {
            $collection->filterByName($validator->getValue('name'));
        }
        $collection->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'areas' => $areas, 'current_area_id' => $areaid, 'records' => $records));
    }

    public function chooseAction($areaid) {
        $area = App::getModel('global/area')->load($areaid);
        return $this->viewResult(array(
            'modules' => App::getHelper('global')->getModules($areaid),
            'area' => $area
        ));
    }

    public function createAction($moduleid, $areaid) {
        $module = App::getModel('global/module')->load($moduleid);
        $area = App::getModel('global/area')->load($areaid);
        $shareBlocks = App::getModel('website/collection_block')
                        ->filterByModuleId($moduleid)
                        ->filterByArea($areaid)
                        ->load();
        $config = Kd_Loader::loadInstance($area->getNamespace().'_module_'.$module->getName().'_config');
        return $this->viewResult(array('share_blocks'=>$shareBlocks,
            'module' => $module, 'area' => $area, 'module_config' => $config));
    }

    public function editAction($id) {
        $model = App::getModel('website/block')->load($id);
        $result = $this->createAction($model->getModuleId(), $model->getAreaId())->setModel($model);
        $result->getShareBlocks()->removeItemById($id);
        return $result;
    }

    public function copyAction($id) {
        $model = App::getModel('website/block')->load($id);
        $model->setCode('')->setId('')->setName('');
        return $this->createAction($model->getModuleId(), $model->getAreaId())
                    ->setModel($model)
                    ->setActionName('create');
    }

//    public function sortAction($template,$position){
//        $modules = App::getModel('website/collection_block')->filterByTemplate($template)->filterByPosition($position)->load();
//        return $this->viewResult(array('modules'=>$modules));
//    }

//    public function sortPostAction() {
//        $sorting = $this->getRequest()->getForm('sorting');
//        $table = App::getModel('website/block')->getTable();
//        foreach ($sorting as $index => $id) {
//            $table->updateSorting($id, $index + 1);
//        }
//        return $this->redirectResult($this->getHistoryUrl('website/block/index'));
//    }

    public function applyPostAction() {
        return $this->saveModel(FALSE);
    }

    public function savePostAction() {
        return $this->saveModel();
    }

//    private function getModuleConfig($areaNs, $moduleName) {
//        $result = NULL;
//        $className = $areaNs . '_module_' . $moduleName . '_config';
//        $subPath = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ', $className))) . '.php';
//        foreach (Kdf_Package::getIncludePaths() as $path) {
//            if (file_exists($path . $subPath)) {
//                $result = new $className();
//                break;
//            }
//        }
//
//        if (is_null($result)) {
//            $result = Kdf_Factory::findInstance($areaNs . '_module_' . $moduleName . '_config');
//        }
//        return $result;
//    }

    private function saveModel($return = TRUE) {
        $namespace = $this->getRequest()->getForm('namespace');
        echo $namespace;
        $data = $this->getRequest()->getForm('module');
        $model = App::getModel('website/block');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $config = Kd_Loader::loadInstance($namespace.'_module_'.$this->getRequest()->getForm('modulename').'_config');
        $data['parameters'] = $config->processParameters($data['parameters']);
        $model->addData($data)->setCreatorId(Kd_Web::getIdentity()->getId());
        if (($errors = $model->validate() === TRUE)) {
            $model->save();
            if(!$model->getShareTemplateName()){
                file_put_contents(DP_TMP.DS.'block'.DS.'template'.DS.$namespace.DS.$model->getCode().'.phtml', $model->getTemplateScript());
            }
            $this->getMessager()->addInform($this->__f('share.message.saveSuccess', '{share.label.module}', $model->getName()));
            return $return ?
                    $this->redirectResult($this->getHistoryUrl('website/block/index')) :
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit'));
        } else {
            $this->getMessager()->addError($this->__f('share.message.saveFail', '{share.label.module}', $model->getName()))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

}